import { login, getUserInfo, getUserDeatilById } from '@/api/user'
import { getToken, setToken, removeToken, setTimestamp } from '@/utils/auth'
import { resetRouter } from '@/router' // 导入重置路由的方法

const state = {
  // token: 'b31747f8-7344-4d4a-a1b2-ad0b22dfda19',
  token: getToken() || '', // token
  userInfo: {} // 用户资料
}
const mutations = {
  SET_TOKEN: (state, token) => {
    // 设置token
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN: (state) => {
    // 移除token
    state.token = ''
    removeToken()
  },
  SET_USERINFO: (state, data) => {
    // 设置用户信息
    state.userInfo = data
  },
  REMOVE_USERINFO: (state) => {
    // 删除用户信息
    state.userInfo = {}
  }
}

const actions = {
  // 登录+获取token
  async login(context, data) {
    const result = await login(data)
    context.commit('SET_TOKEN', result)
    setTimestamp() // 存时间戳
  },

  // 退出登录
  logout(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('REMOVE_USERINFO')
    resetRouter() // 重置路由
    context.commit('permission/SET_ROUTES', [], { root: true })
  },

  // 获取用户基本资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    // 获取用户头像
    const baseInfo = await getUserDeatilById(result.userId)
    const baseResult = { ...result, ...baseInfo }
    context.commit('SET_USERINFO', baseResult)
    return result // 用于后面做权限管理
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
